import React, { Component } from 'react'
import {
  Text,
  TextInput,
  View,
  Image,
  StyleSheet,
  DeviceEventEmitter,
  Platform,
  PixelRatio,
  ScrollView,
  Dimensions,
  AlertIOS,
  Animated,
  RefreshControl,
  TouchableOpacity,
  FlatList,
} from 'react-native'
import { ListItem, Body } from 'native-base'
import Swipeout from 'react-native-swipeout'
import Icon from 'react-native-vector-icons/Ionicons'
import KeyboardAwareFlatList from 'react-native-keyboard-aware-scroll-view/lib/KeyboardAwareFlatList'

import CheckBox from '../component/CheckBox'
import CartBar from '../component/CartBar'
import RootView from '../component/RootView'
import Empty from '../component/Empty'
import Base from './Base'
import {
  NavigationActions,
  px2dp,
  accAdd,
  accMul,
  getBorderWidth,
  imageServer,
} from '../utils'
import * as userService from '../services/user'
import * as cartService from '../services/cart'

const { width, height } = Dimensions.get('window')
const borderWidth = getBorderWidth()

const PIC_SIZE = px2dp(64)

class CartSingle extends Base {
  constructor(props) {
    super(props)
    this.state = {
      isAllowScroll: true,
      data: [],
      checkedString: '',
      totalPrice: 0,
      unchecked: '',
      requestTimes: 0,
    }
    this.subscription = null
  }
  static navigationOptions = {
    title: '购物车',
    headerBackTitle: null,
    headerTitleStyle: {
      alignSelf: 'center',
    },
    headerStyle: {
      backgroundColor: '#fff',
      borderBottomWidth: 0,
      shadowColor: 'transparent',
      elevation: 0,
    },
    headerRight: <View />,
  }

  addItem(productId, num) {
    this.updateCart(productId, num + 1)
  }
  minusItem(productId, num) {
    this.updateCart(productId, num - 1)
  }
  updateCart(productId, num) {
    const params = {
      id: productId,
      num,
    }

    if (num == 0) {
      cartService.removeLocal(params).then(data => {
        DeviceEventEmitter.emit('cart.reload', 'cartSingle')
        this.loadData()
      })
      return
    }

    cartService.updateLocal(params).then(data => {
      DeviceEventEmitter.emit('cart.reload', 'cartSingle')
      this.loadData()
    })
  }
  loadData() {
    const { requestTimes } = this.state
    // 购物车暂时只做本地
    cartService.queryLocal().then(data => {
      // 数据处理
      let str = ''
      let checkedString = ''
      let unchecked = ''
      data.map((item, i) => {
        // 获取未被选中的item
        if (!item.checked) {
          unchecked += `${item.id}#`
        } else {
          checkedString += `|${item.id}#${item.num}`
        }
        str += `|${item.id}#${item.num}`
      })

      cartService
        .view({ data: str, unchecked })
        .then(data => {
          this.setState({
            requestTimes: requestTimes + 1,
            checkedString: checkedString.substr(1),
            data: data.list,
            totalPrice: data.totalPrice,
            unchecked,
          })
        })
        .catch(e => {
          this.checkError(e)
        })
    })
  }
  onEvent(key) {
    if (key != 'cartSingle') {
      this.loadData()
    }
  }
  check(productId, checked) {
    const params = {
      id: productId,
      checked: !checked,
    }

    cartService.updateLocal(params).then(data => {
      this.loadData()
    })
  }
  checkAll(checked) {
    cartService.checkAllLocal(!checked).then(data => {
      this.loadData()
    })
  }
  removeItem(productId) {
    cartService.removeLocal({ id: productId }).then(data => {
      DeviceEventEmitter.emit('cart.reload', 'cartSingle')
      this.loadData()
    })
  }
  async checkIn() {
    // 判断数量
    const checkedString = this.state.checkedString
    if (!checkedString) {
      return
    }
    await this.checkLogin()
    this.goto('OrderConfirm', { data: checkedString })
  }
  renderItem = ({ item, index }) => {
    const swipeoutBtns = [
      {
        text: '删除',
        backgroundColor: '#e23f3c',
        onPress: this.removeItem.bind(this, item.id),
      },
    ]
    let top = 0
    if (index == 0) {
      top = 10
    }
    return (
      <Swipeout
        key={String(index)}
        style={{ marginTop: top }}
        onOpen={() => {
          this.setState({ isAllowScroll: false })
        }}
        onClose={() => {
          this.setState({ isAllowScroll: true })
        }}
        right={swipeoutBtns}
      >
        <View style={styles.itemWrap}>
          <View style={{ width: 24, justifyContent: 'center' }}>
            <CheckBox
              checked={!!item.checked}
              color="#e23f3c"
              onPress={() => this.check(item.id, item.checked)}
            />
          </View>
          <View style={styles.item}>
            <View style={{ justifyContent: 'center' }}>
              <TouchableOpacity
                activeOpacity={0.95}
                onPress={() =>
                  this.goto('Goods', { goodsId: item.id, isSku: 1 })}
              >
                <Image
                  source={{ uri: imageServer + item.image }}
                  style={{
                    backgroundColor: '#fff',
                    width: PIC_SIZE,
                    height: PIC_SIZE,
                    resizeMode: 'contain',
                    marginRight: 8,
                  }}
                />
              </TouchableOpacity>
            </View>
            <View style={{ flex: 1, justifyContent: 'center' }}>
              <TouchableOpacity
                activeOpacity={0.95}
                onPress={() =>
                  this.goto('Goods', { goodsId: item.id, isSku: 1 })}
              >
                <Text numberOfLines={1}>{item.name}</Text>
                <Text style={{ marginTop: 5, fontSize: 12, color: '#999' }}>
                  {item.spec}
                </Text>
                <View style={styles.priceView}>
                  <Text
                    style={{ flex: 1, color: '#e23f3c' }}
                  >{`￥${item.price}`}</Text>
                </View>
              </TouchableOpacity>
            </View>

            <View style={styles.actionView}>
              <TouchableOpacity
                style={styles.minusBtn}
                onPress={() => this.minusItem(item.id, item.num)}
              >
                <Icon
                  name={'ios-remove-circle-outline'}
                  size={px2dp(24)}
                  color="#999"
                />
              </TouchableOpacity>
              <TextInput
                value={String(item.num)}
                editable={false}
                underlineColorAndroid="transparent"
                style={{
                  width: 25,
                  padding: 0,
                  textAlign: 'center',
                  color: '#333',
                }}
              />
              <TouchableOpacity
                style={styles.addBtn}
                onPress={() => this.addItem(item.id, item.num)}
              >
                <Icon
                  name={'ios-add-circle-outline'}
                  size={px2dp(24)}
                  color="#999"
                />
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Swipeout>
    )
  }
  onModalClose = () => {
    this.setState({
      msg: null,
    })
  }
  componentWillUnmount() {
    this.subscription.remove()
  }
  componentDidMount() {
    this.subscription = DeviceEventEmitter.addListener(
      'cart.reload',
      this.onEvent.bind(this)
    )
    this.loadData()
  }
  render() {
    const {
      requestTimes,
      fetching,
      msg,
      data,
      totalPrice,
      unchecked,
    } = this.state
    if (requestTimes > 0 && data.length == 0) {
      return <Empty text="购物车是空的" />
    }
    let all = false
    if (unchecked == '') {
      all = true
    }
    return (
      <RootView
        fetching={fetching}
        hasModal={false}
        modalVisible={!!msg}
        modalView={<Text>{msg}</Text>}
        onModalClose={() => this.onModalClose()}
        style={styles.container}
      >
        <KeyboardAwareFlatList
          scrollEnabled={this.state.isAllowScroll}
          data={data}
          keyExtractor={(item, index) => String(index)}
          keyboardShouldPersistTaps="always"
          renderItem={this.renderItem}
        />

        <CartBar
          totalPrice={totalPrice}
          all={all}
          onCheckAll={checked => this.checkAll(checked)}
          onCheckIn={() => this.checkIn()}
        />
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  itemWrap: {
    flex: 1,
    borderBottomWidth: borderWidth,
    borderBottomColor: '#e5e5e5',
    backgroundColor: '#fff',
    paddingVertical: 10,
    paddingHorizontal: 16,
    flexDirection: 'row',
  },
  item: {
    flex: 1,
    flexDirection: 'row',
  },

  minusBtn: {
    backgroundColor: 'transparent',
  },
  addBtn: {
    backgroundColor: 'transparent',
  },
  priceView: {
    marginTop: 5,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'transparent',
  },
  actionView: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
})

export default CartSingle
